/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Army.task;

import Army.BuildingAndUnit;
import java.awt.Point;

/**
 *
 * @author Huy
 */
public class TaskGuard extends Task {

	Task mainTask;

	public TaskGuard(BuildingAndUnit source, BuildingAndUnit target) {
		super(source, target);
		taskName = "Guard";
		if (!source.isTaskCompleted()) {

			mainTask = source.getTask();
			if (mainTask != null && mainTask.getName().equals(taskName)) {
				mainTask = ((TaskGuard) mainTask).mainTask;
			}
		} else {
			mainTask = null;
		}
	}

	@Override
	public boolean execute() {
		if (isDone) {
			return true;
		}
		Point position;
		if (mainTask == null || mainTask.isDone) {

			position = source.getPosition();
		} else {
			if ("Detroy".equals(mainTask.getName())&& mainTask.target.isUnit()) {
				return mainTask.execute();
			}
			position = mainTask.getPosisition();
		}
		if (target.isAlive()
				&& position.distance(target.getPosition()) < source.getViewRange() + 2 * source.getAttackRange()) {

			int dx = Math.abs(target.getPosition().x - source.getPosition().x);
			int dy = Math.abs(target.getPosition().y - source.getPosition().y);
			double d = Math.max(dx, dy);

			source.setTarget(target.getPosition());

			if (d < source.getAttackRange() + target.getSize() / 2) {
				source.attack();
			} else {
				source.run();
			}
			return false;
		}
		source.idle();
		isDone = true;
		source.setTask(mainTask);
		return true;
	}
}
